package com.yex.service;

import com.baomidou.mybatisplus.plugins.Page;
import com.yex.base.Constant;
import com.yex.base.WalletOper;
import com.yex.base.WalletOperEnum;
import com.yex.constant.AppConstant;
import com.yex.entity.UserEntity;
import com.yex.entity.WalletEntity;
import com.yex.entity.otc.*;
import com.yex.service.otc.*;
import com.yex.utils.FileUtil;
import com.yex.utils.JsonResultVo;
import com.yex.utils.MathUtil;
import com.yex.utils.Utils;
import com.yex.utils.vo.*;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lizhijun
 * @version V1
 * @date Created in 2018/12/26 9:10
 * @description 描述
 */
@Service
public class OtcService {
    @Autowired
    private IOtcCoinService otcCoinService;

    @Autowired
    private IOtcFeeConfigService otcFeeConfigService;

    @Autowired
    private IOtcDayAmountService otcDayAmountService;

    @Autowired
    private IOtcEntrustService otcEntrustService;

    @Autowired
    private IOtcAppealService otcAppealService;

    @Autowired
    private IOtcOrderService otcOrderService;

    @Autowired
    private IOtcVoucherService otcVoucherService;
    @Autowired
    private ApiService apiService;   
    @Autowired
    private WalletService walletService;
    @Autowired
    private LocaleMessageSourceService message;

    //每页显示多少条数据
    private int numPerPage = 10;
    /**
     * otc 币种
     * @param request
     * @return
     */
    public String otcCoinList(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        JsonResultVo jsonResultVo = otcCoinService.otcCoinList();

        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        //String exchange = redisService.getConfig("exchange").toString();
        List<OtcCoin> coinList = (List<OtcCoin>) jsonResultVo.getData();
        List<Map<String,Object>> coinListMap=new ArrayList<>();
        for (OtcCoin otcCoin : coinList) {
            Map<String,Object> coin=new HashMap<>();
            coin.put("id",otcCoin.getId());
            coin.put("coinName",otcCoin.getCoinName());
            //TickerVO ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
            //coin.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
            coin.put("lastPrice","0.00");
            //BigDecimal tickerPrice = otcLastPriceService.findOtcLastPriceBy24Price(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
            BigDecimal tickerPrice =BigDecimal.ZERO;
            BigDecimal rose = MathUtil.ZERO;
            try {
//                rose = MathUtil.getBigDecimal(MathUtil
//                        .mul(MathUtil.div(MathUtil.sub(ticker.getLast(), tickerPrice), tickerPrice), MathUtil.ONEHUNDRED), 2);
            } catch (Exception e) {
            }
            //ticker.setRose(rose);
            //coin.put("rose",ticker.getRose());
            coin.put("rose","");
            coinListMap.add(coin);
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",coinListMap);
        return jsonObject.toString();
    }

    /**
     * otc 委托列表
     * @param request
     * @return
     */
    public String otcEntrustList(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer coinId = Integer.parseInt(request.getParameter("coinId"));
        JsonResultVo  jsonResultVo= otcEntrustService.otcEntrustList(coinId,null);
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",jsonResultVo.getData());
        return jsonObject.toString();
    }

    /**
     * otc 用户委托列表
     * @param request
     * @return
     */
    public String otcEntrustUserList(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        JsonResultVo jsonResultVo = otcEntrustService.otcAppEntrustUserList(fuser.getId());
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",jsonResultVo.getData());
        return jsonObject.toString();
    }

    /**
     * otc 暂停委托订单
     * @param request
     * @return
     */
    public String suspendOtcEntrust(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer entrustId = Integer.parseInt(request.getParameter("entrustId"));
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        JsonResultVo jsonResultVo = otcEntrustService.suspendOtcEntrust(entrustId, fuser.getId());
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",jsonResultVo.getData());
        return jsonObject.toString();
    }

    /**
     * otc 取消委托订单
     * @param request
     * @return
     */
    public String cancelOtcEntrust(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer entrustId = Integer.parseInt(request.getParameter("entrustId"));
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        JsonResultVo jsonResultVo = otcEntrustService.cancelOtcEntrust(entrustId, fuser.getId());
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",jsonResultVo.getData());
        return jsonObject.toString();
    }

    /**
     * otc 用户信息
     * @param request
     * @return
     */
    public String otcUserInfo(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer coinId = Integer.parseInt(request.getParameter("coinId"));

        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);

        try {
            WalletOper walletOper=new WalletOper();
            walletOper.setUserId(fuser.getId());
            walletOper.setOper(WalletOperEnum.ADD);
            walletOper.setAmount(BigDecimal.ZERO);
            this.walletService.updateWallet(walletOper);
        }catch(Exception e) {
            e.printStackTrace();
        }

        JsonResultVo otcCoinJsonResult = otcCoinService.findOtcCoin(coinId);
        if (!otcCoinJsonResult.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, otcCoinJsonResult.getMsg());
            return jsonObject.toString();
        }
        OtcCoin otcCoin = (OtcCoin) otcCoinJsonResult.getData();
        WalletEntity otcWallet =walletService.selectByUserId( fuser.getId());
        if (otcWallet==null ||otcWallet.getId()==null) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, message.getMessage("code_error"));
            return jsonObject.toString();
        }

//        String domain = Constant.Domain;
//        if ("true".equals(Constant.IS_OPEN_OSS)) {
//            domain = Constant.OSSURL;
//        }

        Map<String, Object> infoMap = new HashMap<>(16);

        infoMap.put("fees", otcCoin.getFees());
        infoMap.put("rate", otcCoin.getRate());
        OtcFeeConfig configByUserId = otcFeeConfigService.findOtcFeeConfigByUserId(fuser.getId());
        if(configByUserId!=null){
            infoMap.put("fees", MathUtil.mul(configByUserId.getEntrustFee(),new BigDecimal("100")));
            infoMap.put("rate", MathUtil.mul(configByUserId.getOrderFee(),new BigDecimal("100")));
        }

        infoMap.put("fees", Utils.rvZeroAndDot(MathUtil.getBigDecimalString(new BigDecimal(infoMap.get("fees").toString()))));
        infoMap.put("rate", Utils.rvZeroAndDot(MathUtil.getBigDecimalString(new BigDecimal(infoMap.get("rate").toString()))));

        infoMap.put("ensureAmount", otcCoin.getEnsureAmount());
        infoMap.put("total", otcWallet.getTotal());
        infoMap.put("frozen", otcWallet.getFrozen());
        infoMap.put("totalSum", MathUtil.add(otcWallet.getTotal(),otcWallet.getFrozen()));
        //JsonResultVo userOtcOrderCount = otcOrderCountService.findUserOtcOrderCount(fuser.getId());

        infoMap.put("orderCount", 0);
        infoMap.put("complete", 0);
//        if (userOtcOrderCount.getData() == null) {
//            infoMap.put("orderCount", 0);
//            infoMap.put("complete", 0);
//        } else {
//            OtcOrderCount data = (OtcOrderCount) userOtcOrderCount.getData();
//            BigDecimal addNum = MathUtil.add(new BigDecimal(String.valueOf(data.getSuccessOrderNum())), new BigDecimal(String.valueOf(data.getSysNum())));
//            infoMap.put("orderCount", addNum);
//            if (addNum.compareTo(BigDecimal.ZERO) == 0) {
//                infoMap.put("complete", 0);
//            } else {
//                BigDecimal divNum = MathUtil.div(new BigDecimal(String.valueOf(data.getSuccessOrderNum())), new BigDecimal(addNum + ""));
//                infoMap.put("complete", getBigDecimalString(MathUtil.mul(getBigDecimal(divNum, 4), new BigDecimal("100")), 2));
//            }
//        }
        //String quota = constantService.getString("quota");
        String quota ="";
        String[] quotas = quota.split("-");
        infoMap.put("quota", 200);
        infoMap.put("email", 0);
        infoMap.put("validateStatus", 0);
        infoMap.put("telephoneBind", 0);
        infoMap.put("userPayAccount", 0);
        infoMap.put("level", 0);
        if (fuser.getValidateStatus() >= 3) {
            infoMap.put("quota", quotas[0]);
        }
        if (fuser.getValidateStatus() == 5 || fuser.getValidateStatus() >= 7) {
            infoMap.put("quota", quotas[1]);
        }
        if (fuser.getValidateStatus() == 9) {
            infoMap.put("quota", quotas[2]);
        }
        infoMap.put("email", fuser.getUsername());
        infoMap.put("validateStatus", fuser.getValidateStatus() < 3 ? 0 : 1);
        infoMap.put("telephoneBind", fuser.getTelValidate() == 1 ? 1 : 0);
        infoMap.put("headImg", fuser.getIdentityPath());
        //FuserPayAccount fuserPayAccount = fuserPayAccountService.selectByUserId(fuser.getId());
        boolean fuserPayAccount=true;
        if (fuserPayAccount) {
            infoMap.put("userPayAccount", 0);
        }  else {
            infoMap.put("userPayAccount", 1);
        }
        int level = 0;
        if (fuser.getValidateStatus() >= 3) {
            level = 1;
        }
        if (fuser.getValidateStatus() == 5 || fuser.getValidateStatus() >= 7) {
            level = 2;
        }
        if (fuser.getValidateStatus() == 9) {
            level = 3;
        }
        infoMap.put("level", level);

        Map<String, Object> otcDayAmount = (Map<String, Object>) otcDayAmountService.findOtcDayAmount(fuser.getId()).getData();
        infoMap.put("dayAmount", 0);
        if (otcDayAmount != null) {
            infoMap.put("dayAmount", otcDayAmount.get("amount"));
        }

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",infoMap);
        return jsonObject.toString();
    }

    /**
     * otc 保存委托订单
     * @param request
     * @return
     */
    public String saveOtcEntrust(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();

        Integer coinId = Integer.parseInt(request.getParameter("coinId"));
        Integer type = Integer.parseInt(request.getParameter("type"));
        BigDecimal prize = new BigDecimal(request.getParameter("prize"));
        BigDecimal count = new BigDecimal(request.getParameter("count"));
        String autoIndexStr = request.getParameter("autoIndex");
        String floatingStr = request.getParameter("floating");
        String explain = request.getParameter("explain");
        String limitAmount = request.getParameter("limitAmount");


        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Integer autoIndex = null;
        if (Utils.hasLength(autoIndexStr)) {
            if (!Utils.hasLength(floatingStr)) {
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value,  ( "app_info80"));
                return jsonObject.toString();
            }

            autoIndex = Integer.parseInt(request.getParameter("autoIndex"));
            if (autoIndex > 0) {
                if (new BigDecimal(floatingStr).compareTo(BigDecimal.ZERO) != 1) {
                    jsonObject.accumulate(AppConstant.CODE, -1);
                    jsonObject.accumulate(AppConstant.Value, ( "otc_info_28"));
                    return jsonObject.toString();
                }
            }
        }

        if (Utils.hasLength(limitAmount)) {
            String[] split = limitAmount.split("-");
            if (!Utils.hasLength(split[0])) {
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, ( "app_info80"));
                return jsonObject.toString();
            }
            if (!Utils.hasLength(split[1])) {
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, ( "app_info80"));
                return jsonObject.toString();
            }
        }

        OtcEntrust otcEntrust = new OtcEntrust();
        otcEntrust.setPrize(prize);
        otcEntrust.setSeveral(count);
        otcEntrust.setType(type);
        otcEntrust.setAutoIndex(autoIndex);
        otcEntrust.setFloating(new BigDecimal(floatingStr));
        otcEntrust.setCoinId(coinId);
        otcEntrust.setUserId(fuser.getId());
        otcEntrust.setMarket(4);

        otcEntrust.setLimitAmount(limitAmount);
        otcEntrust.setExplain(explain);

        JsonResultVo jsonResultVo = otcEntrustService.saveOtcEntrust(otcEntrust);
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",jsonResultVo.getData());
        return jsonObject.toString();
    }

    /**
     * otc 第三方市场
     * @param request
     * @return
     */
    public String otcMarket(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer coinId = Integer.parseInt(request.getParameter("coinId"));
        JsonResultVo jsonResultVo = otcCoinService.findOtcCoin(coinId);
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        OtcCoin otcCoin = (OtcCoin) jsonResultVo.getData();
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>(16);
        //String exchange = redisService.getConfig("exchange").toString();

        TickerVO ticker =new TickerVO();
        if (true) {
            map.put("id", AutoIndexEnum.COINMARKETCAP);
            map.put("name", "COINMARKETC");
            //ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
            map.put("lastPrice","0.00");
            map.put("rose",ticker.getRose());
            mapList.add(map);
        }
//        if (Integer.valueOf(otcCoin.getCoinId().toString()).equals(Integer.valueOf(Constant.USDT_ID))) {
//            map.put("id", AutoIndexEnum.COINMARKETCAP);
//            map.put("name", "COINMARKETC");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//        } else if (Integer.valueOf(otcCoin.getCoinId().toString()).equals(Integer.valueOf("4"))) {
//            map.put("id", AutoIndexEnum.COINMARKETCAP);
//            map.put("name", "COINMARKETC");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//            map = new HashMap<>(16);
//            map.put("id", AutoIndexEnum.BITFINEX);
//            map.put("name", "BITFINEX");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.BITFINEX);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//            map = new HashMap<>(16);
//            map.put("id", AutoIndexEnum.HUOBI);
//            map.put("name", "HUOBI");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.HUOBI);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//            map = new HashMap<>(16);
//            map.put("id", AutoIndexEnum.OKCOIN);
//            map.put("name", "OKEX");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.OKCOIN);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//        } else {
//            map.put("id", AutoIndexEnum.COINMARKETCAP);
//            map.put("name", "COINMARKETC");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//            map = new HashMap<>(16);
//            map.put("id", AutoIndexEnum.BITFINEX);
//            map.put("name", "BITFINEX");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.BITFINEX);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//            map = new HashMap<>(16);
//            map.put("id", AutoIndexEnum.BINANCE);
//            map.put("name", "BINANCE");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.BINANCE);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//            map = new HashMap<>(16);
//            map.put("id", AutoIndexEnum.HUOBI);
//            map.put("name", "HUOBI");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.HUOBI);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//            map = new HashMap<>(16);
//            map.put("id", AutoIndexEnum.OKCOIN);
//            map.put("name", "OKEX");
//            ticker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.OKCOIN);
//            map.put("lastPrice",MathUtil.getBigDecimal(MathUtil.mul(ticker.getLast(), new BigDecimal(exchange)), 2));
//            map.put("rose",ticker.getRose());
//            mapList.add(map);
//        }

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",mapList);
        return jsonObject.toString();
    }

    /**
     * 法币账户
     * @param request
     * @return
     */
    public String otcAccount(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);

        try {
            WalletOper walletOper=new WalletOper();
            walletOper.setUserId(fuser.getId());
            walletOper.setOper(WalletOperEnum.ADD);
            walletOper.setAmount(BigDecimal.ZERO);
            this.walletService.updateWallet(walletOper);
            //this.walletService.insertOtcWallet(fuser.getId());
        }catch(Exception e) {
            e.printStackTrace();
        }

        WalletEntity otcWallet = walletService.selectByUserId(fuser.getId());
        if (otcWallet==null || otcWallet.getId()==null) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, message.getMessage("code_error"));
            return jsonObject.toString();
        }
        List<Map<String, Object>> listMap = new ArrayList<>();
        //usdt 价格
        String newUsdtPrize = "1";
//        Ftrademapping paramFtrademapping = new Ftrademapping();
//        paramFtrademapping.setFstatus(TrademappingStatusEnum.ACTIVE);
//        paramFtrademapping.setFvirtualcointype1(Integer.valueOf(Constant.USDT_ID));
//        paramFtrademapping.setFvirtualcointype2(Integer.valueOf(Constant.BTC_ID));
//        List<Ftrademapping> ftrademappingUsdt = ftrademappingService.queryFtrademappingListByAll(paramFtrademapping);
//        if (ftrademappingUsdt.size() == 1) {
//            BigDecimal latestDealPrize = redisService.getNewPrize(ftrademappingUsdt.get(0).getFid());
//            //Usdt最新价
//            newUsdtPrize = getBigDecimalString(latestDealPrize,ftrademappingUsdt.get(0).getFcount1());
//        }
        //虚拟钱包
//        Map<Integer, Ftrademapping> tradeMappings = redisService.getFtrademappingsByCoinType2();
        //总资产
        BigDecimal otcTotalAsset = BigDecimal.ZERO;
//        for (OtcWallet otcWallet : otcWalletList) {
//            OtcCoin otcCoin = otcCoinService.selectById(otcWallet.getCoinId());
//            otcWallet.setAll(MathUtil.add(otcWallet.getTotal(),otcWallet.getFrozen()));
//            BigDecimal asset = BigDecimal.ZERO;
//            BigDecimal total = otcWallet.getAll();
//            if (!tradeMappings.containsKey(otcCoin.getCoinId())) {
//                BigDecimal btcCount = new BigDecimal(newUsdtPrize);
//                BigDecimal usdtCount = new BigDecimal("1");
//                BigDecimal usdtPrice =MathUtil.div(usdtCount, btcCount);
//                BigDecimal usdtTotalCount = total;
//                BigDecimal btcMoney = getBigDecimal(MathUtil.mul(usdtPrice, usdtTotalCount), 8);
//                asset = btcMoney;
//            } else {
//                //转换 btc
//                asset = this.rechargeService.getRechargeBtc(otcCoin.getCoinId(), total);
//            }
//            otcWallet.setBtcAsset(asset);
//
//            Fvirtualwallet fvirtualwallet = fvirtualwalletService.selectFvirtualwalletTotalAndFrozenByUserIdAndCoinId(fuser.getId(), otcCoin.getCoinId());
//            otcWallet.setCoinTotal(fvirtualwallet.getfTotal());
//
//            BigDecimal temp2 = new BigDecimal(newUsdtPrize);
//            BigDecimal temp1 = MathUtil.mul(temp2, new BigDecimal(constantService.getString("exchange").trim()));
//            BigDecimal cny1 = MathUtil.mul(temp1, asset);
//            String  btcAssetCny="";
//            if (cny1.compareTo(BigDecimal.valueOf(0.01)) == -1) {
//                btcAssetCny = MathUtil.getBigDecimalString(cny1, 4);
//            } else {
//                btcAssetCny = MathUtil.getBigDecimalString(cny1, 2);
//            }
//            otcWallet.setBtcAssetCny(btcAssetCny);
//            otcTotalAsset = MathUtil.getBigDecimal(MathUtil.add(otcTotalAsset, asset));
//            Map<String, Object> infoMap = new HashMap<>(16);
//            infoMap.put("id",otcWallet.getId());
//            infoMap.put("coinId",otcWallet.getCoinId());
//            infoMap.put("total",MathUtil.getBigDecimalString(otcWallet.getTotal()));
//            infoMap.put("frozen",MathUtil.getBigDecimalString(otcWallet.getFrozen()));
//            infoMap.put("coinName",otcWallet.getCoinName());
//            infoMap.put("coinTotal",MathUtil.getBigDecimalString(otcWallet.getCoinTotal()));
//            infoMap.put("all",MathUtil.getBigDecimalString(otcWallet.getAll()));
//            infoMap.put("btcAsset",MathUtil.getBigDecimalString(otcWallet.getBtcAsset()));
//            infoMap.put("btcAssetCny",otcWallet.getBtcAssetCny());
//            listMap.add(infoMap);
//        }

        Map<String, Object> infoMap = new HashMap<>(16);
        infoMap.put("id",otcWallet.getId());
        infoMap.put("coinId",otcWallet.getUserId());
        infoMap.put("total",MathUtil.getBigDecimalString(otcWallet.getTotal()));
        infoMap.put("frozen",MathUtil.getBigDecimalString(otcWallet.getFrozen()));
        infoMap.put("coinName","");
        infoMap.put("coinTotal",MathUtil.getBigDecimalString(otcWallet.getTotal()));
        infoMap.put("all",MathUtil.getBigDecimalString(otcWallet.getTotal()));
        infoMap.put("btcAsset",MathUtil.getBigDecimalString(otcWallet.getTotal()));
        infoMap.put("btcAssetCny",otcWallet.getTotal());
        listMap.add(infoMap);

//        BigDecimal cny2 = MathUtil.mul(MathUtil.mul(new BigDecimal(newUsdtPrize), new BigDecimal(constantService.getString("exchange").trim())), otcTotalAsset);
//        String  otcWalletBtcCny="";
//        if (cny2.compareTo(BigDecimal.valueOf(0.01)) == -1) {
//            otcWalletBtcCny = MathUtil.getBigDecimalString(cny2, 4);
//        } else {
//            otcWalletBtcCny = MathUtil.getBigDecimalString(cny2, 2);
//        }
        String otcWalletBtcCny = MathUtil.getBigDecimalString(new BigDecimal(0.01), 4);

        JSONObject otcAccount = new JSONObject();
        otcAccount.accumulate("otcWalletList",listMap);
        otcAccount.accumulate("otcWalletBtcCny",otcWalletBtcCny);
        otcAccount.accumulate("otcTotalAsset", MathUtil.getBigDecimalString(otcTotalAsset));

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",otcAccount);
        return jsonObject.toString();
    }

//    /**
//     * 法币币币 互转
//     * @param request
//     * @return
//     */
//    public String rotationOtcWallet(HttpServletRequest request) {
//        JSONObject jsonObject = new JSONObject();
//        Integer coinId = Integer.parseInt(request.getParameter("coinId"));
//        Integer type = Integer.parseInt(request.getParameter("type"));
//        BigDecimal number = new BigDecimal(request.getParameter("number"));
//        String token = request.getParameter("token");
//        UserEntity fuser = apiService.verifyToken(token);
//
//        JsonResultVo jsonResultVo = walletService.updateRotationOtcWallet(coinId, fuser.getId(), type, number);
//        if (!jsonResultVo.isSuccess()) {
//            jsonObject.accumulate(AppConstant.CODE, -1);
//            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
//            return jsonObject.toString();
//        }
//
//        jsonObject.accumulate(AppConstant.CODE, 0);
//        jsonObject.accumulate(AppConstant.Value, ( "success"));
//        jsonObject.accumulate("data","");
//        return jsonObject.toString();
//    }


    /**
     * 下单
     * @param request
     * @return
     */
    public String otcOrder(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer id = Integer.parseInt(request.getParameter("id"));
        BigDecimal number = new BigDecimal(request.getParameter("number"));
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        JsonResultVo jsonResultVo = otcOrderService.addOrder(id, number, fuser.getId());
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        OtcOrder data = (OtcOrder) jsonResultVo.getData();
        Map<String,Object> map=new HashMap<>();
        map.put("id",data.getId());
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("success_ordered"));
        jsonObject.accumulate("data",map);
        return jsonObject.toString();
    }

    /**
     * 订单信息
     * @param request status（0未完成 1已完成 2已取消）
     * @return
     */
    public String otcOrderInfo(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer status = Integer.parseInt(request.getParameter("status"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        if (currentPage == null) {
            currentPage = 1;
        }
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Map<String, Object> map = new HashMap<>();
        OtcOrder queryOtcOrder = new OtcOrder();
        queryOtcOrder.setUserId(fuser.getId());
        queryOtcOrder.setStatus(status);
        Page<Map<String,Object>> page = new Page<>(currentPage, numPerPage);
        page = otcOrderService.selectOtcOrderMapPage(queryOtcOrder,page);
        List<Map<String, Object>> dataMap = new ArrayList<>();
        Map<String, Object> prams = new HashMap<>();
        Date nowDate = new Date();
        for (Map<String, Object> rm : page.getRecords()) {
//            FuserPayAccount fuserPayAccount = null;
//            if (Integer.parseInt(rm.get("type").toString())==0) {
//                fuserPayAccount = fuserPayAccountService.selectByUserId(ObjectUtils.toInteger(rm.get("entrustUserId") + ""));
//                String domain = Constant.Domain;
//                if ("true".equals(Constant.IS_OPEN_OSS)) {
//                    domain = Constant.OSSURL;
//                }
//                fuserPayAccount.setfAlipayCode(domain+fuserPayAccount.getfAlipayCode());
//                fuserPayAccount.setfWenxinCode(domain+fuserPayAccount.getfWenxinCode());
//            } else {
//                fuserPayAccount = fuserPayAccountService.selectByUserId(ObjectUtils.toInteger(rm.get("userId") + ""));
//                String domain = Constant.Domain;
//                if ("true".equals(Constant.IS_OPEN_OSS)) {
//                    domain = Constant.OSSURL;
//                }
//                fuserPayAccount.setfAlipayCode(domain+fuserPayAccount.getfAlipayCode());
//                fuserPayAccount.setfWenxinCode(domain+fuserPayAccount.getfWenxinCode());
//            }

            if (Integer.parseInt(rm.get("entrustType").toString())==0) {
                BigDecimal countNum = MathUtil.sub(new BigDecimal(rm.get("countNum").toString()), new BigDecimal(rm.get("fees").toString()));
                if(!fuser.getId().equals(rm.get("userId"))) {
                    rm.put("countNum",countNum);
                    BigDecimal entrustRate = MathUtil.div(new BigDecimal(rm.get("entrustRate").toString()), new BigDecimal("100"));
                    rm.put("fees",MathUtil.getBigDecimal(MathUtil.mul(new BigDecimal(rm.get("countNum").toString()),entrustRate),8));
                }
                rm.put("amount", MathUtil.getBigDecimal(MathUtil.mul(countNum,new BigDecimal(rm.get("prize").toString())),2));
            }else {
                if(!fuser.getId().equals(rm.get("userId"))) {
                    BigDecimal entrustRate = MathUtil.div(new BigDecimal(rm.get("entrustRate").toString()), new BigDecimal("100"));
                    BigDecimal dealFees =  MathUtil.getBigDecimal(MathUtil.mul(new BigDecimal(rm.get("countNum").toString()),entrustRate),8);
                    rm.put("fees",dealFees);
                }
                rm.put("amount", MathUtil.getBigDecimal(MathUtil.mul(new BigDecimal(rm.get("countNum").toString()),new BigDecimal(rm.get("prize").toString())),2));
            }
            if(fuser.getId().equals(rm.get("userId"))) {
                rm.put("uRealName", rm.get("eRealName"));
            }
            if(!fuser.getId().equals(rm.get("userId"))) {
                rm.put("type",rm.get("entrustType"));
            }
            int isShowAppeal = 0;
            Date d = null;
            rm.put("nowTime",nowDate.getTime());
            rm.put("isCanCancel",0);
            if(Integer.parseInt(rm.get("status").toString())==OtcOperEnum.PAYED) {
                Date payDate = (Date)rm.get("payDateTime");
                long timestamp = payDate.getTime();
                rm.put("startTime",timestamp);
                rm.put("endTime",(timestamp+60*60*1000*12L));
                //卖家申述
                if (Integer.parseInt(rm.get("type").toString())==1&&fuser.getId().equals(rm.get("userId"))) {
                    isShowAppeal = 1;
                }else if(Integer.parseInt(rm.get("entrustType").toString())==1&&fuser.getId().equals(rm.get("entrustUserId"))) {
                    isShowAppeal = 1;
                }
            }else if(Integer.parseInt(rm.get("status").toString())==OtcOperEnum.INIT_STATUS) {
                Date createDate = (Date)rm.get("createTime");
                long timestamp = createDate.getTime();
                rm.put("startTime",timestamp);
                rm.put("endTime",(timestamp+1000*60*15L));
            }else if(Integer.parseInt(rm.get("status").toString())==OtcOperEnum.SELLER_COMPLAINT) {
                //买家取消
                if (Integer.parseInt(rm.get("type").toString())==0&&fuser.getId().equals(rm.get("userId"))) {
                    rm.put("isCanCancel",1);
                }else if(Integer.parseInt(rm.get("entrustType").toString())==0&&fuser.getId().equals(rm.get("entrustUserId"))) {
                    rm.put("isCanCancel",1);
                }
            }else {
                rm.put("startTime",nowDate.getTime());
                rm.put("endTime",nowDate.getTime());
            }

            if(rm.get("upVoucherStatus")==null){
                rm.put("upVoucherStatus",0);
            }

            if(rm.get("serversStatus")==null){
                rm.put("serversStatus",0);
            }

            if(rm.get("arbitrationStatus")==null){
                rm.put("arbitrationStatus",0);
            }
            Object eRealName=rm.get("eRealName");
            Object uRealName=rm.get("uRealName");
            Object eValidateStatus=rm.get("eValidateStatus");
            Object uValidateStatus=rm.get("uValidateStatus");
            Object eTel=rm.get("eTel");
            Object uTel=rm.get("uTel");
            if(fuser.getId().equals(Integer.valueOf(rm.get("userId").toString()))){
                rm.put("eRealName",uRealName);
                rm.put("eValidateStatus",uValidateStatus);
                rm.put("eTel",uTel);
                rm.put("uRealName",eRealName);
                rm.put("uValidateStatus",eValidateStatus);
                rm.put("uTel",eTel);
            } else {
                rm.put("eRealName",eRealName);
                rm.put("eValidateStatus",eValidateStatus);
                rm.put("eTel",eTel);
                rm.put("uRealName",uRealName);
                rm.put("uValidateStatus",uValidateStatus);
                rm.put("uTel",uTel);
            }
            if(d != null) {
                long sec = (d.getTime()-nowDate.getTime())/1000;
                if(sec<0) {
                    sec = 0;
                }
                rm.put("sec",sec);
            }
            rm.put("isShowAppeal", isShowAppeal);
            //rm.put("ayAccount", fuserPayAccount);//支付信息
            rm.put("ayAccount", "");//支付信息
            dataMap.add(rm);
        }

        map.clear();
        map.put("reList", dataMap);
        map.put("currentPage", currentPage);
        map.put("numPerPage", numPerPage);
        map.put("totalCount", page.getTotal());

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("success"));
        jsonObject.accumulate("data",map);
        return jsonObject.toString();
    }

    /**
     * 订单信息详情
     * @param request status（0未完成 1已完成 2已取消）
     * @return
     */
    public String otcOrderDetails(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer id = Integer.parseInt(request.getParameter("id"));

        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);

        Map<String, Object>  rm = otcOrderService.selectOtcOrderMapById(id,fuser.getId());

        Map<String, Object> prams = new HashMap<>();
        Date nowDate = new Date();

//        FuserPayAccount fuserPayAccount = null;
//        if (Integer.parseInt(rm.get("type").toString())==0) {
//            fuserPayAccount = fuserPayAccountService.selectByUserId(ObjectUtils.toInteger(rm.get("entrustUserId") + ""));
//            String domain = Constant.Domain;
//            if ("true".equals(Constant.IS_OPEN_OSS)) {
//                domain = Constant.OSSURL;
//            }
//            fuserPayAccount.setfAlipayCode(domain+fuserPayAccount.getfAlipayCode());
//            fuserPayAccount.setfWenxinCode(domain+fuserPayAccount.getfWenxinCode());
//        } else {
//            fuserPayAccount = fuserPayAccountService.selectByUserId(ObjectUtils.toInteger(rm.get("userId") + ""));
//            String domain = Constant.Domain;
//            if ("true".equals(Constant.IS_OPEN_OSS)) {
//                domain = Constant.OSSURL;
//            }
//            fuserPayAccount.setfAlipayCode(domain+fuserPayAccount.getfAlipayCode());
//            fuserPayAccount.setfWenxinCode(domain+fuserPayAccount.getfWenxinCode());
//        }

        if (Integer.parseInt(rm.get("entrustType").toString())==0) {
            BigDecimal countNum = MathUtil.sub(new BigDecimal(rm.get("countNum").toString()), new BigDecimal(rm.get("fees").toString()));
            if(!fuser.getId().equals(rm.get("userId"))) {
                rm.put("countNum",countNum);
                BigDecimal entrustRate = MathUtil.div(new BigDecimal(rm.get("entrustRate").toString()), new BigDecimal("100"));
                rm.put("fees",MathUtil.getBigDecimalString(MathUtil.mul(new BigDecimal(rm.get("countNum").toString()),entrustRate),8));
            }
            rm.put("amount", MathUtil.getBigDecimal(MathUtil.mul(countNum,new BigDecimal(rm.get("prize").toString())),2));
        }else {
            if(!fuser.getId().equals(rm.get("userId"))) {
                BigDecimal entrustRate = MathUtil.div(new BigDecimal(rm.get("entrustRate").toString()), new BigDecimal("100"));
                String dealFees =  MathUtil.getBigDecimalString(MathUtil.mul(new BigDecimal(rm.get("countNum").toString()),entrustRate),8);
                rm.put("fees",dealFees);
            }
            rm.put("amount", MathUtil.getBigDecimal(MathUtil.mul(new BigDecimal(rm.get("countNum").toString()),new BigDecimal(rm.get("prize").toString())),2));
        }
        if(fuser.getId().equals(rm.get("userId"))) {
            rm.put("uRealName", rm.get("eRealName"));
        }
        if(!fuser.getId().equals(rm.get("userId"))) {
            rm.put("type",rm.get("entrustType"));
        }
        rm.put("fees",MathUtil.getBigDecimalString(new BigDecimal(rm.get("fees").toString()),8));
        int isShowAppeal = 0;
        Date d = null;
        rm.put("nowTime",nowDate.getTime());
        rm.put("isCanCancel",0);
        if(Integer.parseInt(rm.get("status").toString())==OtcOperEnum.PAYED) {
            Date payDate = (Date)rm.get("payDateTime");
            long timestamp = payDate.getTime();
            rm.put("startTime",timestamp);
            rm.put("endTime",(timestamp+60*60*1000*12L));
            //卖家申述
            if (Integer.parseInt(rm.get("type").toString())==1&&fuser.getId().equals(rm.get("userId"))) {
                isShowAppeal = 1;
            }else if(Integer.parseInt(rm.get("entrustType").toString())==1&&fuser.getId().equals(rm.get("entrustUserId"))) {
                isShowAppeal = 1;
            }
        }else if(Integer.parseInt(rm.get("status").toString())==OtcOperEnum.INIT_STATUS) {
            Date createDate = (Date)rm.get("createTime");
            long timestamp = createDate.getTime();
            rm.put("startTime",timestamp);
            rm.put("endTime",(timestamp+1000*60*15L));
        }else if(Integer.parseInt(rm.get("status").toString())==OtcOperEnum.SELLER_COMPLAINT) {
            //买家取消
            if (Integer.parseInt(rm.get("type").toString())==0&&fuser.getId().equals(rm.get("userId"))) {
                rm.put("isCanCancel",1);
            }else if(Integer.parseInt(rm.get("entrustType").toString())==0&&fuser.getId().equals(rm.get("entrustUserId"))) {
                rm.put("isCanCancel",1);
            }
        }else {
            rm.put("startTime",nowDate.getTime());
            rm.put("endTime",nowDate.getTime());
        }

        if(rm.get("upVoucherStatus")==null){
            rm.put("upVoucherStatus",0);
        }

        if(rm.get("serversStatus")==null){
            rm.put("serversStatus",0);
        }

        if(rm.get("arbitrationStatus")==null){
            rm.put("arbitrationStatus",0);
        }

        Object eRealName=rm.get("eRealName");
        Object uRealName=rm.get("uRealName");
        Object eValidateStatus=rm.get("eValidateStatus");
        Object uValidateStatus=rm.get("uValidateStatus");
        Object eTel=rm.get("eTel");
        Object uTel=rm.get("uTel");
        if(fuser.getId().equals(Integer.valueOf(rm.get("userId").toString()))){
            rm.put("eRealName",uRealName);
            rm.put("eValidateStatus",uValidateStatus);
            rm.put("eTel",uTel);
            rm.put("uRealName",eRealName);
            rm.put("uValidateStatus",eValidateStatus);
            rm.put("uTel",eTel);
        } else {
            rm.put("eRealName",eRealName);
            rm.put("eValidateStatus",eValidateStatus);
            rm.put("eTel",eTel);
            rm.put("uRealName",uRealName);
            rm.put("uValidateStatus",uValidateStatus);
            rm.put("uTel",uTel);
        }
        if(d != null) {
            long sec = (d.getTime()-nowDate.getTime())/1000;
            if(sec<0) {
                sec = 0;
            }
            rm.put("sec",sec);
        }
        rm.put("isShowAppeal", isShowAppeal);
        //rm.put("ayAccount", fuserPayAccount);//支付信息
        rm.put("ayAccount", "");//支付信息

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("success"));
        jsonObject.accumulate("data",rm);
        return jsonObject.toString();
    }
    /**
     * 申请仲裁
     * @param request
     * @return
     */
    public String otcArbitration(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Integer id = Integer.parseInt(request.getParameter("id"));

        OtcAppealVo otcAppealVo = new OtcAppealVo();
        otcAppealVo.setOrderId(id);
        otcAppealVo.setOtcAppealOperEnum(OtcAppealOperEnum.APPLY_APPEAL);
        otcAppealVo.setUserId(fuser.getId());
        JsonResultVo jsonResultVo = otcAppealService.updateOtcAppeal(otcAppealVo);

        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("successful_arbitration"));
        jsonObject.accumulate("data","");
        return jsonObject.toString();
    }


    /**
     * 确定收款
     * @param request
     * @return
     */
    public String otcReceivables(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Integer id = Integer.parseInt(request.getParameter("id"));
        String password = request.getParameter("password");

        try {
            if(fuser.getMoneyPassword()==null) {
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, ( "firstSetTradePassword"));
                return jsonObject.toString();
            }
            String md5Pass = DigestUtils.sha256Hex(password);
            if (!md5Pass.equals(fuser.getMoneyPassword())) {
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value,("tradePasswordError"));
                return jsonObject.toString();
            }
            JsonResultVo jsonResultVo = otcOrderService.updateOrder(id, OtcOperEnum.COMFIRM_MONEY, fuser.getId(), null, false);
            if (!jsonResultVo.isSuccess()) {
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
                return jsonObject.toString();
            }
        }catch (Exception e){
            e.printStackTrace();
            return AppConstant.getUnknownError(request, e).toString();
        }

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("confirm_successful_receipt"));
        jsonObject.accumulate("data","");
        return jsonObject.toString();
    }

    /**
     * 买家已付款
     * @param request
     * @return
     */
    public String otcPayment(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Integer id = Integer.parseInt(request.getParameter("id"));
        Integer payMethod = Integer.parseInt(request.getParameter("payMethod"));
        JsonResultVo jsonResultVo = otcOrderService.updateOrder(id, OtcOperEnum.PAYED, fuser.getId(), payMethod, false);
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("auditSuccess"));
        jsonObject.accumulate("data","");
        return jsonObject.toString();
    }


    /**
     * 买家取消
     * @param request
     * @return
     */
    public String otcCancelOrder(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Integer id = Integer.parseInt(request.getParameter("id"));
        JsonResultVo jsonResultVo = otcOrderService.updateOrder(id, OtcOperEnum.BUYER_CANCEL, fuser.getId(),null,false);
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("cancelSuccess"));
        jsonObject.accumulate("data","");
        return jsonObject.toString();
    }

    /**
     * 申请客诉
     * @param request
     * @return
     */
    public String otcAftersale(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Integer id = Integer.parseInt(request.getParameter("id"));
        JsonResultVo jsonResultVo = otcOrderService.updateOrder(id, OtcOperEnum.SELLER_COMPLAINT, fuser.getId(),null,false);
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }

        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("successful_application"));
        jsonObject.accumulate("data","");
        return jsonObject.toString();
    }

    /**
     * 获取联系方式
     * @param request
     * @return
     */
    public String otcContact(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        Integer id = Integer.parseInt(request.getParameter("id"));
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ("success"));
        jsonObject.accumulate("data", otcOrderService.getOrderContact(id, fuser.getId()));
        return jsonObject.toString();
    }

    /**
     * 上传凭证
     * @param request
     * @return
     */
    public String otcUploadVoucher(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer id = Integer.parseInt(request.getParameter("id"));
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        JsonResultVo jsonResultVo =new JsonResultVo();
        String imgStr = "";
        MultipartFile file1 = mRequest.getFile("file1");
        if(file1!=null&&Utils.hasLength(file1.toString())){
            jsonResultVo = otcUploadVoucherImg(request, file1);
            if(jsonResultVo.getCode()==-1){
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
                return jsonObject.toString();
            }
            imgStr+=jsonResultVo.getData().toString()+"#";

        }
        MultipartFile file2 = mRequest.getFile("file2");
        if(file2!=null&&Utils.hasLength(file2.toString())){
            jsonResultVo = otcUploadVoucherImg(request, file2);
            if(jsonResultVo.getCode()==-1){
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
                return jsonObject.toString();
            }
            imgStr+=jsonResultVo.getData().toString()+"#";
        }
        MultipartFile file3 = mRequest.getFile("file3");
        if(file3!=null&&Utils.hasLength(file3.toString())){
            jsonResultVo = otcUploadVoucherImg(request, file3);
            if(jsonResultVo.getCode()==-1){
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
                return jsonObject.toString();
            }
            imgStr+=jsonResultVo.getData().toString()+"#";
        }
        MultipartFile file4 = mRequest.getFile("file4");
        if(file4!=null&&Utils.hasLength(file4.toString())){
            jsonResultVo = otcUploadVoucherImg(request, file4);
            if(jsonResultVo.getCode()==-1){
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
                return jsonObject.toString();
            }
            imgStr+=jsonResultVo.getData().toString()+"#";
        }
        MultipartFile file5 = mRequest.getFile("file5");
        if(file5!=null&&Utils.hasLength(file5.toString())){
            jsonResultVo = otcUploadVoucherImg(request, file5);
            if(jsonResultVo.getCode()==-1){
                jsonObject.accumulate(AppConstant.CODE, -1);
                jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
                return jsonObject.toString();
            }
            imgStr+=jsonResultVo.getData().toString()+"#";
        }
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        if (imgStr.lastIndexOf("#") != -1) {
            imgStr = imgStr.substring(0, imgStr.length() - 1);
        }
        if(imgStr.split("#").length<=0){
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, ( "otc_info_29"));
            return jsonObject.toString();
        }
        OtcAppealVo otcAppealVo = new OtcAppealVo();
        otcAppealVo.setOrderId(id);
        otcAppealVo.setOtcAppealOperEnum(OtcAppealOperEnum.UPLOAD_VOCHER);
        otcAppealVo.setUserId(fuser.getId());
        otcAppealVo.setImgUrls(imgStr.split("#"));
        JsonResultVo jsonResultVo1 = otcAppealService.updateOtcAppeal(otcAppealVo);
        if(!jsonResultVo1.isSuccess()){
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo1.getMsg());
            return jsonObject.toString();
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "uploadSuccess"));
        jsonObject.accumulate("data","");
        return jsonObject.toString();
    }


    /**
     * 上传凭证
     * @param request
     * @return
     */
    private JsonResultVo otcUploadVoucherImg(HttpServletRequest request,MultipartFile multipartFile) {
        JsonResultVo jsonObject = new JsonResultVo();
        Map<String,Object> map = new HashMap<>();
        try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            InputStream inputStream = multipartFile.getInputStream();
            String realName = multipartFile.getOriginalFilename();
            JSONObject resultJson = new JSONObject();
            if (!Utils.hasLength(realName)) {
                jsonObject.setCode(-1);
                jsonObject.setMsg(( "img_format_error"));
                return jsonObject;
            }
            double size = multipartFile.getSize() / 1000d;
            if (size > 5120d) {
                jsonObject.setCode(-1);
                jsonObject.setMsg(( "app_info81"));
                return jsonObject;
            }
            String[] nameSplit = realName.split("\\.");
            String ext = nameSplit[nameSplit.length - 1];
            if (ext != null && !ext.trim().toLowerCase().endsWith("jpg")
                    && !ext.trim().toLowerCase().endsWith("bmp")
                    && !ext.trim().toLowerCase().endsWith("png") && !ext.trim().toLowerCase().endsWith("jpeg")) {
                jsonObject.setCode( -1);
                jsonObject.setMsg(( "img_format_error"));
                return jsonObject;
            }

            String realPath = request.getSession().getServletContext().getRealPath("/") + Constant.uploadPicDirectory;
            String fileName = Utils.getRandomImageName() + "." + ext;
            //FileUtil.saveFile(realPath, fileName, inputStream, Constant.uploadPicDirectory);

//            if (Constant.IS_OPEN_OSS.equals("false")) {
                resultJson.put("resultUrl", "/" + Constant.uploadPicDirectory + "/" + fileName);
//            } else {
//                resultJson.put("resultUrl", OssPostObject.URL + "/" + Constant.uploadPicDirectory + "/" + fileName);
//            }
//            String domain = Constant.Domain;
//            if ("true".equals(Constant.IS_OPEN_OSS)) {
//                domain = Constant.OSSURL;
//            }
//            map.put("imgUrl", domain+resultJson.getString("resultUrl"));
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.setCode(-1);
            jsonObject.setMsg("failedInfo");
            return jsonObject;
        }
        jsonObject.setCode(0);
        jsonObject.setMsg(( "success"));
        jsonObject.setData(map.get("imgUrl"));
        return jsonObject;
    }


    /**
     * 查看凭证
     * @param request
     * @return
     */
    public String otcVoucher(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        Integer id = Integer.parseInt(request.getParameter("id"));
        String token = request.getParameter("token");
        UserEntity fuser = apiService.verifyToken(token);
        OtcVoucher otcVoucher = new OtcVoucher();
        otcVoucher.setOrderId(id);
        otcVoucher.setUserId(fuser.getId());
        JsonResultVo jsonResultVo = otcVoucherService.selectVoucherList(otcVoucher);
        if (!jsonResultVo.isSuccess()) {
            jsonObject.accumulate(AppConstant.CODE, -1);
            jsonObject.accumulate(AppConstant.Value, jsonResultVo.getMsg());
            return jsonObject.toString();
        }
        jsonObject.accumulate(AppConstant.CODE, 0);
        jsonObject.accumulate(AppConstant.Value, ( "success"));
        jsonObject.accumulate("data",jsonResultVo.getData());
        return jsonObject.toString();
    }



}
